<template>
  <div class="home-page">
    <!-- 轮播展示区 -->
    <el-carousel 
      height="400px" 
      :interval="5000" 
      arrow="always" 
      class="carousel-section"
    >
      <el-carousel-item v-for="(item, index) in banners" :key="index">
        <div 
          class="carousel-item" 
          :style="{ backgroundImage: `url(${item.img})` }"
        >
          <div class="carousel-content">
            <h2>{{ item.title }}</h2>
            <p>{{ item.desc }}</p>
            <el-button type="primary" round @click="handleCarouselAction">
              立即查看
            </el-button>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>

    <!-- 简介模块 -->
    <div class="intro-section">
      <el-row :gutter="30" align="middle">
        <el-col :md="12">
          <img 
            src="https://picsum.photos/1200/400?random=3" 
            alt="系统介绍" 
            class="intro-image"
          >
        </el-col>
        <el-col :md="12">
          <div class="intro-content">
            <h3>关于我们</h3>
            <p class="intro-text">
              校园失物招领系统致力于为师生提供高效便捷的失物管理服务，通过信息化手段整合校园资源，构建诚信互助的校园环境。自2020年上线以来，已成功帮助找回失物5000+件。
            </p>
            <el-divider />
            <div class="stats">
              <div v-for="(stat, index) in stats" :key="index" class="stat-item">
                <div class="stat-value">{{ stat.value }}+</div>
                <div class="stat-label">{{ stat.label }}</div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
<el-dialog 
    v-model="detailVisible" 
    :title="detailTitle" 
    width="50%"
    class="detail-dialog"
  >
    <div v-if="currentDetail">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="物品名称">{{ currentDetail.itemName }}</el-descriptions-item>
        <el-descriptions-item label="类别">{{ currentDetail.itemCategory }}</el-descriptions-item>
        <el-descriptions-item label="地点">
        {{ isFoundDetail ? (currentDetail as FindItemDTO).foundLocation : (currentDetail as LostItemDTO).lostLocation }}
        </el-descriptions-item>

        <el-descriptions-item label="时间">
        {{ isFoundDetail ? formatTime((currentDetail as FindItemDTO).foundTime) : formatTime((currentDetail as LostItemDTO).lostTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="详细描述">{{ currentDetail.detailedDescription }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">
          {{ isFoundDetail ? (currentDetail.phone) : (currentDetail.phone) }}
        </el-descriptions-item>
        <el-descriptions-item label="图片" v-if="currentDetail.image">
        <el-image 
         :src="`http://localhost:8080/${currentDetail.image}`" 
         style="max-width: 200px; max-height: 200px"
         :preview-src-list="[`http://localhost:8080/${currentDetail.image}`]"
         />
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </el-dialog>
    <!-- 核心展示模块 -->
    <div class="core-section">
      <!-- 招领信息 -->
      <h3 class="section-title">最新招领信息</h3>
      <el-row :gutter="20" class="card-row">
  <el-col 
    v-for="(item, index) in foundItems" 
    :key="'found'+index" 
    :md="8"
  >
    <el-card 
      class="info-card" 
      shadow="hover"
      @click="showDetail(item, true)"
    >
            <div class="card-header">
              <el-tag type="success">招领</el-tag>
              <span class="item-name">{{ item.itemName }}</span>
            </div>
            <div class="card-content">
              <p><el-icon><Location /></el-icon> {{ item.foundLocation }}</p >
              <p><el-icon><Clock /></el-icon> {{ item.foundTime }}</p>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 失物信息 -->
      <h3 class="section-title" style="margin-top: 40px">最新失物信息</h3>
      <el-row :gutter="20" class="card-row">
  <el-col 
    v-for="(item, index) in lostItems" 
    :key="'lost'+index" 
    :md="8"
  >
    <el-card 
      class="info-card" 
      shadow="hover"
      @click="showDetail(item, false)"
    >
            <div class="card-header">
              <el-tag type="danger">失物</el-tag>
              <span class="item-name">{{ item.itemName }}</span>
            </div>
            <div class="card-content">
              <p><el-icon><Location /></el-icon> {{ item.lostLocation }}</p>
              <p><el-icon><Clock /></el-icon> {{ item.lostTime }}</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { Location, Clock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const detailVisible = ref(false);
const currentDetail = ref<FindItemDTO | LostItemDTO | null>(null);
const isFoundDetail = ref(false);
interface FindItemDTO {
  id: number;
  itemName: string;
  itemCategory: string;
  foundLocation: string;
  foundTime: Date;
  detailedDescription: string; // 新增字段
  phone?: string;
  image?: string;
}

interface LostItemDTO {
  id: number;
  itemName: string;
  itemCategory: string;
  lostLocation: string;
  lostTime: Date;
  detailedDescription: string; // 新增字段
  phone?: string;
  image?: string;
}
// 定义类型接口
interface BannerItem {
  img: string;
  title: string;
  desc: string;
}

interface StatItem {
  value: number;
  label: string;
}

interface InfoFItem extends Omit<FindItemDTO, 'foundTime'> {
  foundTime: string; // 前端展示用字符串
}

interface InfoLItem extends Omit<LostItemDTO, 'lostTime'> {
  lostTime: string; // 前端展示用字符串
}
// 轮播数据
const banners = ref<BannerItem[]>([
  {
    img: 'https://picsum.photos/1200/400?random=1',
    title: '快速发布失物信息',
    desc: '三步完成登记，高效寻找失物'
  },
  {
    img: 'https://picsum.photos/1200/400?random=2',
    title: '智能匹配系统',
    desc: 'AI算法精准匹配失物信息'
  }
])
const detailTitle = computed(() => 
  isFoundDetail.value ? '招领详情' : '失物详情'
);
// 统计信息
const stats = ref<StatItem[]>([
  { value: 5000, label: '成功案例' },
  { value: 98, label: '找回率' },
  { value: 99, label: '用户满意度' }
])
const token = localStorage.getItem('token')
const headers = token ? { Authorization: `Bearer ${token}` } : {}

const handleApiError = (error: any) => {
  console.error('API Error:', error)
  
  if (error.response) {
    const { status } = error.response
    
    switch (status) {
      case 401:
        ElMessage.warning('请先登录')
        router.push('/login')
        break
      case 403:
        ElMessage.error('权限不足，无法访问此内容')
        break
      case 404:
        ElMessage.error('请求的资源不存在')
        break
      default:
        ElMessage.error(`请求失败: ${error.message}`)
    }
  } else {
    ElMessage.error('网络错误，请检查连接')
  }
}

// 招领/失物数据（添加类型注解）
const foundItems = ref<InfoFItem[]>([])
const lostItems = ref<InfoLItem[]>([])
// 在showDetail方法中添加类型断言
const showDetail = async (item: InfoFItem | InfoLItem, isFound: boolean) => {
  try {
    // 每次请求前获取最新token
    const token = localStorage.getItem('token');
    const headers = token ? { headers: { Authorization: `Bearer ${token}` } } : {};
    
    const endpoint = isFound ? `/find/ById/${item.id}` : `/lost/ById/${item.id}`;
    const { data } = await axios.get<FindItemDTO | LostItemDTO>(endpoint, headers);
    
    currentDetail.value = data;
    isFoundDetail.value = isFound;
    detailVisible.value = true;
  } catch (error) {
    ElMessage.error('获取详情失败');
    console.error('Error fetching detail:', error);
  }
};

const formatTime = (dateString: string | Date) => {
  const date = new Date(dateString);
  return date.toLocaleString();
};
// 获取最新数据
const fetchLatestData = async () => {
  try {
    const [foundRes, lostRes] = await Promise.all([
      axios.get<{ data: InfoFItem[] }>('/find/latest',{headers}),
      axios.get<{ data: InfoLItem[] }>('/lost/latest',{headers})
    ]);

    // 打印响应数据
    console.log("招领接口响应:", foundRes.data);
    console.log("失物接口响应:", lostRes.data);

    // 数据映射
    foundItems.value = foundRes.data.data.map(item => ({
  id: item.id,
  itemName: item.itemName,
  itemCategory: item.itemCategory,
  foundLocation: item.foundLocation,
  foundTime: formatTime(item.foundTime),
  detailedDescription: item.detailedDescription, // 新增
  image: item.image
}));

lostItems.value = lostRes.data.data.map(item => ({
  id: item.id,
  itemName: item.itemName,
  itemCategory: item.itemCategory,
  lostLocation: item.lostLocation,
  lostTime: formatTime(item.lostTime),
  detailedDescription: item.detailedDescription, // 新增
  image: item.image
}));
  } catch (error) {
    ElMessage.error('数据加载失败');
    console.error("请求失败:", error);
  }
};

// 轮播点击事件（添加类型断言）
const handleCarouselAction = () => {
  const coreSection = document.querySelector('.core-section') as HTMLElement | null
  if (coreSection) {
    window.scrollTo({
      top: coreSection.offsetTop - 80,
      behavior: 'smooth'
    })
  }
}

onMounted(() => {
  fetchLatestData()
})
</script>

<style scoped>
.home-page {
  width: 100%;
  max-width: none; /* 移除最大宽度限制 */
  padding: 20px;
  box-sizing: border-box;
}
.el-main.main-content > * {  /* 所有子元素继承宽度 */
  width: 100%;
  max-width: 1400px;  /* 可设置更大值 */
  margin: 0 auto;
}
/* 轮播样式 */
.carousel-section {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.carousel-item {
  height: 400px;
  background-size: cover;
  background-position: center;
  position: relative;
}

.carousel-content {
  position: absolute;
  left: 10%;
  top: 30%;
  color: white;
  text-shadow: 1px 1px 3px rgba(0,0,0,0.5);
  max-width: 500px;
}

.carousel-content h2 {
  font-size: 2.2rem;
  margin-bottom: 1rem;
}

/* 简介模块 */
.intro-section {
  margin: 40px 0;
  padding: 30px 0;
  background: #f8f9fa;
  border-radius: 8px;
}

.intro-image {
  width: 100%;
  height: 300px;
  object-fit: cover;
  border-radius: 8px;
}

.intro-content {
  padding: 0 20px;
}

.intro-text {
  line-height: 1.8;
  color: #666;
}

.stats {
  display: flex;
  justify-content: space-around;
  margin-top: 30px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 28px;
  color: #42b983;
  font-weight: bold;
}

.stat-label {
  color: #666;
  font-size: 14px;
}
/* 添加详情弹窗样式 */
.detail-dialog .el-descriptions__label {
  width: 100px;
  font-weight: bold;
}
.detail-dialog .el-descriptions__content {
  padding-left: 20px;
}
/* 核心信息展示 */
.core-section {
  margin: 40px 0;
}

.section-title {
  font-size: 1.5rem;
  color: #333;
  margin-bottom: 20px;
}

.info-card {
  margin-bottom: 20px;
  transition: transform 0.3s;
}

.info-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.item-name {
  margin-left: 10px;
  font-weight: bold;
}

.card-content {
  color: #666;
}

.card-content p {
  display: flex;
  align-items: center;
  margin: 8px 0;
}

.card-content i {
  margin-right: 8px;
}
</style>